<script setup>
	import { computed, ref, watch } from 'vue'
	import { TableOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons-vue'
	import { message } from 'ant-design-vue'

	const props = defineProps({
		loading: {
			type: Boolean,
			default: false
		},
		data: {
			type: Array,
			default: () => []
		},
		columns: {
			type: Array,
			default: () => []
		},
		selectedColumns: {
			type: Array,
			default: () => []
		}
	})

	const currentView = ref('table')
	const pageSize = ref(10)
	const currentPage = ref(1)

	// 计算显示的列
	const displayColumns = computed(() => {
		if (!props.selectedColumns || props.selectedColumns.length === 0) {
			return props.columns
		}
		return props.columns.filter((col) => props.selectedColumns.includes(col.key))
	})

	// 计算分页数据
	const paginatedData = computed(() => {
		const start = (currentPage.value - 1) * pageSize.value
		const end = start + pageSize.value
		return props.data.slice(start, end)
	})

	// 数据统计信息
	const dataStats = computed(() => {
		if (!props.data || props.data.length === 0) {
			return null
		}

		const totalRows = props.data.length
		const totalColumns = props.columns.length
		const selectedColumnsCount = props.selectedColumns.length

		return {
			totalRows,
			totalColumns,
			selectedColumnsCount,
			dataSize: JSON.stringify(props.data).length
		}
	})

	// 导出数据
	const exportData = () => {
		if (!props.data || props.data.length === 0) {
			message.warning('暂无数据可导出')
			return
		}

		try {
			// 过滤选中的列
			const exportData = props.data.map((row) => {
				const filteredRow = {}
				displayColumns.value.forEach((col) => {
					filteredRow[col.title] = row[col.dataIndex] || row[col.key]
				})
				return filteredRow
			})

			// 转换为CSV格式
			const headers = displayColumns.value.map((col) => col.title).join(',')
			const csvContent = exportData
				.map((row) =>
					Object.values(row)
						.map((value) => (typeof value === 'string' && value.includes(',') ? `"${value}"` : value))
						.join(',')
				)
				.join('\n')

			const csv = headers + '\n' + csvContent

			// 下载文件
			const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
			const link = document.createElement('a')
			const url = URL.createObjectURL(blob)
			link.setAttribute('href', url)
			link.setAttribute('download', `api_data_${Date.now()}.csv`)
			link.style.visibility = 'hidden'
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)

			message.success('数据导出成功')
		} catch (error) {
			console.error('导出失败:', error)
			message.error('数据导出失败')
		}
	}

	// 格式化数据大小
	const formatDataSize = (bytes) => {
		if (bytes < 1024) return bytes + ' B'
		if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
		return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
	}

	// 监听数据变化，重置分页
	watch(
		() => props.data,
		() => {
			currentPage.value = 1
		}
	)
</script>

<template>
	<div class="flex flex-col h-full">
		<!-- 头部工具栏 -->
		<div class="flex items-center justify-between p-4 border-b bg-gray-50">
			<div class="flex items-center space-x-4">
				<div class="flex items-center space-x-2">
					<table-outlined class="text-blue-500" />
					<span class="font-medium">数据预览</span>
				</div>

				<!-- 数据统计 -->
				<div v-if="dataStats" class="flex items-center space-x-4 text-sm text-gray-600">
					<span>{{ dataStats.totalRows }} 行</span>
					<span>{{ dataStats.selectedColumnsCount }}/{{ dataStats.totalColumns }} 列</span>
					<span>{{ formatDataSize(dataStats.dataSize) }}</span>
				</div>
			</div>

			<div class="flex items-center space-x-2">
				<!-- 视图切换 -->
				<a-radio-group v-model="currentView" size="small">
					<a-radio-button value="table">表格</a-radio-button>
					<a-radio-button value="json">JSON</a-radio-button>
				</a-radio-group>

				<!-- 导出按钮 -->
				<a-button :disabled="!props.data || props.data.length === 0" size="small" @click="exportData">
					<download-outlined />
					导出
				</a-button>
			</div>
		</div>

		<!-- 内容区域 -->
		<div class="flex-1 overflow-hidden">
			<!-- 加载状态 -->
			<div v-if="loading" class="flex items-center justify-center h-full">
				<a-spin size="large" />
				<span class="ml-3 text-gray-600">正在加载数据...</span>
			</div>

			<!-- 无数据状态 -->
			<div v-else-if="!props.data || props.data.length === 0" class="flex items-center justify-center h-full">
				<a-empty description="暂无数据">
					<template #image>
						<eye-outlined style="font-size: 48px; color: #d9d9d9" />
					</template>
					<div class="text-gray-500 mt-2">请选择API接口并配置参数后执行查询</div>
				</a-empty>
			</div>

			<!-- 表格视图 -->
			<div v-else-if="currentView === 'table'" class="h-full overflow-auto">
				<a-table
					:columns="displayColumns"
					:data-source="paginatedData"
					:pagination="{
						current: currentPage,
						pageSize: pageSize,
						total: props.data.length,
						showSizeChanger: true,
						showQuickJumper: true,
						showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
						onChange: (page, size) => {
							currentPage = page
							pageSize = size
						}
					}"
					:scroll="{ x: 'max-content', y: 'calc(100vh - 300px)' }"
					bordered
					size="small"
				>
					<template #bodyCell="{ text }">
						<div :title="text" class="max-w-xs truncate">
							{{ text }}
						</div>
					</template>
				</a-table>
			</div>

			<!-- JSON视图 -->
			<div v-else class="h-full overflow-auto p-4">
				<pre class="bg-gray-50 p-4 rounded-lg text-sm overflow-auto">{{ JSON.stringify(props.data, null, 2) }}</pre>
			</div>
		</div>

		<!-- 底部状态栏 -->
		<div v-if="props.data && props.data.length > 0" class="border-t bg-gray-50 px-4 py-2">
			<div class="flex items-center justify-between text-xs text-gray-600">
				<div>显示 {{ displayColumns.length }} 个字段，共 {{ props.data.length }} 条记录</div>
				<div v-if="props.selectedColumns.length > 0">已选择 {{ props.selectedColumns.length }} 个字段用于数据集</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.ant-table {
		background: white;
	}

	.ant-table-tbody > tr > td {
		padding: 8px 12px;
	}

	.ant-table-thead > tr > th {
		padding: 8px 12px;
		background: #fafafa;
	}

	pre {
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-size: 12px;
		line-height: 1.4;
		max-height: calc(100vh - 200px);
	}

	.max-w-xs {
		max-width: 200px;
	}
</style>
